<template>
    <div class="notice-bar" :style="{ background, color }" v-show="showStatus">
        <IconPlus name="notice"></IconPlus>
        <div ref="containerRef" class="text-container">
            <!-- 如果不需要滚动，则直接显示居中文本 -->
            <span v-if="!needScroll" ref="contentRef" class="content no-scroll">
                {{ text }}
            </span>

            <!-- 需要滚动时，显示两个span，实现无缝滚动 -->
            <template v-else>
                <!-- 第一个span用于测量宽度和展示滚动文本 -->
                <span ref="contentRef" class="content scroll" :style="animationStyle" @mouseenter="handleHover(true)"
                    @mouseleave="handleHover(false)">
                    {{ text }}
                </span>
                <!-- 克隆的文本 -->
                <span class="content scroll cloned" :style="animationStyle" @mouseenter="handleHover(true)"
                    @mouseleave="handleHover(false)">
                    {{ text }}
                </span>
            </template>
        </div>
        <IconPlus name="ele-CircleClose" class="closeBtn" @click="handleClose"></IconPlus>
    </div>
</template>

<script setup>
import { ref, computed, onMounted, watch, nextTick } from 'vue'

// 定义 props，使用你给出的默认值
const {
    text = '',
    speed = 50,
    autoplay = true,
    background = 'var(--el-bg-color-page)',
    color = 'var(--el-color-warning)'
} = defineProps({
    text: String,
    speed: Number,
    autoplay: Boolean,
    background: String,
    color: String,
})
const showStatus = ref(true);
const containerRef = ref(null)
const contentRef = ref(null)
const containerWidth = ref(0)
const contentWidth = ref(0)
const isHovering = ref(false)

// 只有当 autoplay 为 true 且内容宽度大于容器宽度时启用滚动
const needScroll = computed(() => {
    return autoplay || contentWidth.value > containerWidth.value
})

// 动画时长：总滚动距离为内容宽度加容器宽度，除以 speed 得到时长
const animationDuration = computed(() => {
    if (!needScroll.value || contentWidth.value <= 0 || speed <= 0) return '0s'
    const distance = contentWidth.value + containerWidth.value
    return `${distance / speed}s`
})

// 动画样式
const animationStyle = computed(() => ({
    animationDuration: animationDuration.value,
    animationPlayState: isHovering.value ? 'paused' : 'running',
    // 绑定CSS自定义变量（核心修改点）
    '--translate-max': `-${containerWidth.value}px`,  // 格式化为带%的字符串
    '--translate-min': `-${contentWidth.value}px`
}))

// 鼠标悬停，暂停动画
const handleHover = (hover) => {
    if (!autoplay) return
    isHovering.value = hover
}

const initSize = () => {
    if (!containerRef.value || !contentRef.value) return
    containerWidth.value = containerRef.value.offsetWidth
    // 使用 scrollWidth 得到内容实际宽度
    contentWidth.value = contentRef.value.scrollWidth;
}

const handleClose = () => {
    showStatus.value = false;
}

onMounted(() => {
    nextTick(() => {
        initSize()
        window.addEventListener('resize', debounce(initSize, 200))
    })
})

// 当文本发生改变时，等待 DOM 更新后重新计算尺寸
watch(() => text, async () => {
    await nextTick()
    initSize()
})

// 简单的防抖函数
const debounce = (fn, delay = 100) => {
    let timer
    return (...args) => {
        clearTimeout(timer)
        timer = setTimeout(() => fn(...args), delay)
    }
}
</script>

<style lang="scss" scoped>
.notice-bar {
    display: flex;
    align-items: center;
    padding: 10px 16px;
    font-size: 14px;
    overflow: hidden;
    box-sizing: border-box;
    width: 100%;
    height: auto;
}

.text-container {
    cursor: pointer;
    flex: 1;
    position: relative;
    overflow: hidden;
    white-space: nowrap;
    display: flex;
    align-items: center;
    padding: 0px 10px;
    height: 1em;
}


/* 当不滚动时，让内容居中显示 */
.content.no-scroll {
    width: 100%;
    text-align: center;
    white-space: nowrap;
}


/* 滚动文本样式 */
.content.scroll {
    display: inline-block;
    white-space: nowrap;
    position: absolute;
    will-change: transform;
    animation-name: marquee;
    animation-timing-function: linear;
    animation-iteration-count: infinite;
}

/* 克隆的文本起始位置放在右侧 */
.content.scroll.cloned {
    position: absolute;
    left: 100%;
}

/* 定义滚动动画：从 container 右侧滚入到完全离开 container 左侧 */
@keyframes marquee {
    0% {
        transform: translateX(var(--translate-min));
    }

    100% {
        transform: translateX(var(--translate-max));
    }
}

.closeBtn {
    cursor: pointer;
}
</style>